package com.smh.myreflect2;

import com.smh.myreflect1.Student;

import java.lang.reflect.Field;

public class ConstructorDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
//        Class类中用于获取成员变量的方法
//        Field[]getFields():返回所有公共成员变量对象的数组
//        Field[] getDeclaredFields():返回所有成员变量对象的数组
//        Field getField(String name):返回单个公共成员变量对象
//        Field getDeclaredField(String name):返回单个成员变量对象
//        Field类中用于创建对象的方法
//        void set(Object obj, Object value):赋值
//        Object get(Object obj) 获取值。

        Class<?> c = Class.forName("com.smh.myreflect1.Student");

        //获取成员变量
        Field[] fields = c.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("---------------");
        Field[] declaredFields = c.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        System.out.println("-------------");

        //gender是私有的,获取不到
//        Field field = c.getField("gender");
//        System.out.println(field);

        Field declaredField = c.getDeclaredField("age");
        System.out.println(declaredField);
        System.out.println("-------------------");
        //权限修饰符
        int modifiers = declaredField.getModifiers();
        System.out.println(modifiers);
        //变量名
        String name = declaredField.getName();
        System.out.println(name);
        //变量类型
        Class<?> type = declaredField.getType();
        System.out.println(type);
        //获取成员变量的值
        Student student = new Student("asd", 12, "nan");
        declaredField.setAccessible(true);//应为是私有的,所以要先关闭权限校验
        Object o = declaredField.get(student);
        System.out.println(o);

        //修改
        declaredField.set(student, 17);
        Object o1 = declaredField.get(student);
        System.out.println(o1);

    }
}
